package org.example.new_hbps_backend_reconstruction.service;

/**
 * @author 丁利军
 * @date 2025年10月16日 11:33
 * @description 心永的腕表的用户配置服务
 */

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.example.new_hbps_backend_reconstruction.common.results.R;
import org.example.new_hbps_backend_reconstruction.utils.HTTPUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserConfigService {

    private static final String SAVE_OR_UPDATE_URL = "https://open.heart-forever.com/api/ext/saveOrUpdateUserConfigs";
    private static final String LIST_USER_CONFIG_URL = "https://open.heart-forever.com/api/ext/listUserConfig";
    @Autowired
    private HTTPUtils httpUtils;
    @Autowired
    private PatientDeviceV2Service patientDeviceV2Service;

    private static final String PRE_CALIBRATION_URL = "https://open.heart-forever.com/api/ext/measure";
    /**
     * 调用预标定接口
     *
     * @param patientUid 用户的patientUid
     * @param sbp 收缩压
     * @param dbp 舒张压
     * @param hr 心率
     * @return R<?> 返回成功或失败的结果
     */
    public R<?> setPreCalibration(Long patientUid, int sbp, int dbp, int hr) {
        // 创建请求参数
        Map<String, Object> params = new HashMap<>();
        params.put("sbp", sbp);
        params.put("dbp", dbp);
        params.put("hr", hr);

        Object obj = patientDeviceV2Service.generateUserAuthToken(patientUid);
        if(obj instanceof String userAccessToken){
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.set("user_access_token", userAccessToken);
            // 发送POST请求
            JSONObject response = httpUtils.post(PRE_CALIBRATION_URL, params, headers);

            // 检查返回值并返回相应结果
            if (response.getIntValue("code") == 0) {
                return R.ok("预标定成功");
            } else {
                return R.failed(response.getString("msg"));
            }
        }else{
            return R.failed("获取用户授权失败");
        }

    }
    /**
     * 根据 patientUid 获取 user_access_token
     */
    public R<?> getUserAccessTokenByUid(Long uid) {
        if (uid == null || uid <= 0) {
            return R.failed("无效的uid");
        }
        Object obj = patientDeviceV2Service.generateUserAuthToken(uid);
        if (obj instanceof String token) {
            // 直接把 token 返回给前端
            return R.ok(token, "ok");
        }
        // 非字符串即表示底层已返回错误信息，这里统一包装给前端
        return R.failed(obj, "获取用户授权失败");
    }

    /**
     * 设置白天静默测量间隔
     */
    public R<?> setDaytimeInterval(String userAccessToken, int intervalSeconds) {
        Map<String, Object> body = new HashMap<>();
        JSONArray configList = new JSONArray();

        JSONObject config = new JSONObject();
        config.put("key", "bp_silent_measurement_interval");
        // 0 启用
        config.put("value", "0");
        config.put("property", String.valueOf(intervalSeconds));

        configList.add(config);
        body.put("configList", configList);

        JSONObject response = postWithToken(userAccessToken, body);
        return parseResponse(response, "设置白天静默测量间隔");
    }

    /**
     * 设置夜间静默测量间隔
     */
    public R<?> setNightInterval(String userAccessToken, int intervalSeconds) {
        Map<String, Object> body = new HashMap<>();
        JSONArray configList = new JSONArray();

        JSONObject config = new JSONObject();
        config.put("key", "bp_silent_measurement_night_interval");
        // 0 启用
        config.put("value", "0");
        config.put("property", String.valueOf(intervalSeconds));

        configList.add(config);
        body.put("configList", configList);

        JSONObject response = postWithToken(userAccessToken, body);
        return parseResponse(response, "设置夜间静默测量间隔");
    }

    /**
     * 设置静默测量白天时间段（例如：06,22）
     */
    public R<?> setDaytimeRange(String userAccessToken, String startHour, String endHour) {
        Map<String, Object> body = new HashMap<>();
        JSONArray configList = new JSONArray();

        JSONObject config = new JSONObject();
        config.put("key", "silent_daytime_range");
        // 0 启用
        config.put("value", "0");
        config.put("property", startHour + "," + endHour);

        configList.add(config);
        body.put("configList", configList);

        JSONObject response = postWithToken(userAccessToken, body);
        return parseResponse(response, "设置静默测量白天时间段");
    }

    /**
     * 公共请求封装：带 token 的 POST 请求
     */
    private JSONObject postWithToken(String userAccessToken, Map<String, Object> body) {
        MultiValueMap<String, String> headersMap = new LinkedMultiValueMap<>();
        headersMap.add("user_access_token", userAccessToken);
        headersMap.add("Content-Type", "application/json; charset=utf-8");
        return httpUtils.post(SAVE_OR_UPDATE_URL, body, headersMap);
    }

    /**
     * 解析 API 响应并封装为 R
     */
    private R<?> parseResponse(JSONObject response, String actionName) {
        if (response == null) {
            return R.failed(actionName + "失败：无响应");
        }
        Integer code = response.getInteger("code");
        String msg = response.getString("msg");
        Object data = response.get("data");

        if (code != null && code == 0) {
            return R.ok(data, actionName + "成功");
        } else {
            return R.failed(data, actionName + "失败：" + msg);
        }
    }
    /**
     * 开启/关闭自动测量（白天+夜间）
     */
    public R<?> switchAutoMeasure(String userAccessToken, boolean enable, int intervalSeconds) {
        Map<String, Object> body = new HashMap<>();
        JSONArray configList = new JSONArray();

        // value = 0 启用，1 关闭
        String value = enable ? "0" : "1";

        // 白天配置
        JSONObject dayConfig = new JSONObject();
        dayConfig.put("key", "bp_silent_measurement_interval");
        dayConfig.put("value", value);
        dayConfig.put("property", String.valueOf(intervalSeconds));

        // 夜间配置
        JSONObject nightConfig = new JSONObject();
        nightConfig.put("key", "bp_silent_measurement_night_interval");
        nightConfig.put("value", value);
        nightConfig.put("property", String.valueOf(intervalSeconds));

        configList.add(dayConfig);
        configList.add(nightConfig);
        body.put("configList", configList);

        JSONObject response = postWithToken(userAccessToken, body);
        return parseResponse(response, enable ? "开启自动测量" : "关闭自动测量");
    }
    /**
     * 设置静默测量模式
     * 对应文档 key: silent_measurement_ppg_enabled
     * value: 0 开启，1 关闭
     * property: 0 脉搏波(PPG)，1 示波法
     */
    public R<?> setSilentMode(String userAccessToken, boolean enable, Integer method) {
        // 基本校验：method 只能是 0 或 1
        if (method == null || (method != 0 && method != 1)) {
            return R.failed("method 取值非法：仅支持 0(脉搏波PPG) 或 1(示波法)");
        }

        Map<String, Object> body = new HashMap<>();
        JSONArray configList = new JSONArray();

        JSONObject config = new JSONObject();
        config.put("key", "silent_measurement_ppg_enabled");
        // 0 开启，1 关闭
        config.put("value", enable ? "0" : "1");
        // 0=PPG, 1=示波法
        config.put("property", String.valueOf(method));

        configList.add(config);
        body.put("configList", configList);

        JSONObject response = postWithToken(userAccessToken, body);
        return parseResponse(response, "设置静默测量模式");
    }
    /**
     * 静默测量白天是否加压
     * key: silent_ppg_daytime_prs
     * value: 0 开启（此处固定为 0）
     * property: 0 不加压，1 加压
     */
    public R<?> setDaytimePressurize(String userAccessToken, boolean pressurize) {
        Map<String, Object> body = new HashMap<>();
        JSONArray configList = new JSONArray();

        JSONObject config = new JSONObject();
        config.put("key", "silent_ppg_daytime_prs");
        // 启用该配置项
        config.put("value", "0");
        config.put("property", pressurize ? "1" : "0");

        configList.add(config);
        body.put("configList", configList);

        JSONObject response = postWithToken(userAccessToken, body);
        return parseResponse(response, "设置静默测量白天是否加压");
    }

    /**
     * 静默测量夜间是否加压
     * key: silent_ppg_nighttime_prs
     * value: 0 开启（此处固定为 0）
     * property: 0 不加压，1 加压
     */
    public R<?> setNightPressurize(String userAccessToken, boolean pressurize) {
        Map<String, Object> body = new HashMap<>();
        JSONArray configList = new JSONArray();

        JSONObject config = new JSONObject();
        config.put("key", "silent_ppg_nighttime_prs");
        // 启用该配置项
        config.put("value", "0");
        config.put("property", pressurize ? "1" : "0");

        configList.add(config);
        body.put("configList", configList);

        JSONObject response = postWithToken(userAccessToken, body);
        return parseResponse(response, "设置静默测量夜间是否加压");
    }
    /**
     * 查询个人配置列表
     * 文档：/api/ext/listUserConfig
     * Header: user_access_token
     * Body: 无
     */
    public R<?> listUserConfigs(String userAccessToken) {
        if (userAccessToken == null || userAccessToken.isBlank()) {
            return R.failed("user_access_token 不能为空");
        }
        // 无请求体，用空 Map 即可（不能传 null，避免序列化为字符串 "null"）
        Map<String, Object> emptyBody = new HashMap<>(0);

        MultiValueMap<String, String> headersMap = new LinkedMultiValueMap<>();
        headersMap.add("user_access_token", userAccessToken);
        headersMap.add("Content-Type", "application/json; charset=utf-8");

        JSONObject resp = httpUtils.post(LIST_USER_CONFIG_URL, emptyBody, headersMap);
        return parseResponse(resp, "查询个人配置");
    }


}
